package com.muyu.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.muyu.common.core.constant.UserConstants;
import com.muyu.common.core.exception.ServiceException;
import com.muyu.common.core.utils.StringUtils;
import com.muyu.common.core.web.page.PageQueryModel;
import com.muyu.common.security.utils.DictUtils;
import com.muyu.common.system.domain.SysDictData;
import com.muyu.common.system.domain.SysDictType;
import com.muyu.system.domain.model.SysDictTypeAddModel;
import com.muyu.system.domain.model.SysDictTypeListModel;
import com.muyu.system.domain.model.SysDictTypePageQueryModel;
import com.muyu.system.domain.model.SysDictTypeUpdModel;
import com.muyu.system.mapper.SysDictTypeMapper;
import com.muyu.system.service.SysDictDataService;
import com.muyu.system.service.SysDictTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author muyu
 */
@Service
public class SysDictTypeServiceImpl extends ServiceImpl<SysDictTypeMapper, SysDictType> implements SysDictTypeService {


    @Autowired
    private SysDictDataService sysDictDataService;

    @Override
    public PageQueryModel<SysDictType> pageQuery(SysDictTypePageQueryModel sysDictDataPageQueryModel) {
        LambdaQueryWrapper<SysDictType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(sysDictDataPageQueryModel.getDictName()),SysDictType::getDictName, sysDictDataPageQueryModel.getDictName());
        queryWrapper.like(StringUtils.isNotEmpty(sysDictDataPageQueryModel.getDictType()),SysDictType::getDictType, sysDictDataPageQueryModel.getDictType());
        queryWrapper.eq(StringUtils.isNotEmpty(sysDictDataPageQueryModel.getStatus()),SysDictType::getDictType, sysDictDataPageQueryModel.getStatus());
        queryWrapper.gt(Objects.nonNull(sysDictDataPageQueryModel.getBeginTime()),SysDictType::getCreateTime, sysDictDataPageQueryModel.getBeginTime());
        queryWrapper.lt(Objects.nonNull(sysDictDataPageQueryModel.getEndTime()),SysDictType::getCreateTime, sysDictDataPageQueryModel.getEndTime());
        Page<SysDictType> page = this.page(sysDictDataPageQueryModel.buildPage(), queryWrapper);
        return PageQueryModel.of(page);
    }

    /**
     * 项目启动时，初始化字典到缓存
     */
    @PostConstruct
    public void init () {
        loadingDictCache();
    }

    /**
     * 根据条件分页查询字典类型
     *
     * @param sysDictTypePageQueryModel 字典类型信息
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictTypeListModel> selectDictTypeList (SysDictTypePageQueryModel sysDictTypePageQueryModel) {
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(sysDictTypePageQueryModel.getDictName()),SysDictType::getDictName, sysDictTypePageQueryModel.getDictName());
        lambdaQueryWrapper.eq(StringUtils.isNotEmpty(sysDictTypePageQueryModel.getStatus()),SysDictType::getStatus, sysDictTypePageQueryModel.getStatus());
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(sysDictTypePageQueryModel.getDictType()),SysDictType::getDictType, sysDictTypePageQueryModel.getDictType());
        Map<String, Object> params = sysDictTypePageQueryModel.getParams();
        Date beginTime = (Date) params.get("beginTime");
        Date endTime = (Date) params.get("endTime");
        lambdaQueryWrapper.between(
                beginTime != null && endTime != null,
                SysDictType::getCreateTime, beginTime, endTime
        );
        List<SysDictType> sysDictTypeList = this.list(lambdaQueryWrapper);
        List<SysDictTypeListModel> sysDictTypeListModelList = sysDictTypeList.stream().map(
                sysDictType -> SysDictTypeListModel.builder()
                        .dictId(sysDictType.getDictId())
                        .dictName(sysDictType.getDictName())
                        .dictType(sysDictType.getDictType())
                        .status(sysDictType.getStatus())
                        .remark(sysDictType.getRemark())
                        .build()
        ).distinct().collect(Collectors.toList());
        return sysDictTypeListModelList;
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    @Override
    public List<SysDictType> selectDictTypeAll () {
        return this.list();
    }

    /**
     * 根据字典类型查询字典数据
     *
     * @param dictType 字典类型
     *
     * @return 字典数据集合信息
     */
    @Override
    public List<SysDictData> selectDictDataByType (String dictType) {
        List<SysDictData> dictDatas = DictUtils.getDictCache(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            return dictDatas;
        }
        dictDatas = sysDictDataService.selectDictDataByType(dictType);
        if (StringUtils.isNotEmpty(dictDatas)) {
            DictUtils.setDictCache(dictType, dictDatas);
            return dictDatas;
        }
        return null;
    }

    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     *
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeById (Long dictId) {
        return this.getById(dictId);
    }

    /**
     * 根据字典类型查询信息
     *
     * @param dictType 字典类型
     *
     * @return 字典类型
     */
    @Override
    public SysDictType selectDictTypeByType (String dictType) {
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDictType::getDictType, dictType);
        return getOne(lambdaQueryWrapper);
    }

    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    @Override
    public void deleteDictTypeByIds (List<Long> dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (sysDictDataService.isChildByType(dictType.getDictType())) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            this.removeById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    @Override
    public void loadingDictCache () {
        List<SysDictData> sysDictDataEnableList = sysDictDataService.findAllByEnable();
        Map<String, List<SysDictData>> dictDataMap = sysDictDataEnableList.stream()
                .collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(
                    entry.getKey(),
                    entry.getValue().stream()
                            .sorted(Comparator.comparing(SysDictData::getDictSort))
                            .toList()
            );
        }
    }

    /**
     * 清空字典缓存数据
     */
    @Override
    public void clearDictCache () {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    @Override
    public void resetDictCache () {
        clearDictCache();
        loadingDictCache();
    }

    /**
     * 新增保存字典类型信息
     *
     * @param sysDictTypeAddModel 字典类型信息
     *
     * @return 结果
     */
    @Override
    public void insertDictType (SysDictTypeAddModel sysDictTypeAddModel) {
        SysDictType sysDictType = SysDictType.builder()
                .dictName(sysDictTypeAddModel.getDictName())
                .dictType(sysDictTypeAddModel.getDictType())
                .status(sysDictTypeAddModel.getStatus())
                .remark(sysDictTypeAddModel.getRemark())
                .build();
        if (this.save(sysDictType)) {
            DictUtils.setDictCache(sysDictType.getDictType(), null);
        }
    }

    /**
     * 修改保存字典类型信息
     *
     * @param sysDictTypeUpdModel 字典类型信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDictType (SysDictTypeUpdModel sysDictTypeUpdModel) {
        SysDictType dict = SysDictType.builder()
                .dictId(sysDictTypeUpdModel.getDictId())
                .dictName(sysDictTypeUpdModel.getDictName())
                .dictType(sysDictTypeUpdModel.getDictType())
                .status(sysDictTypeUpdModel.getStatus())
                .remark(sysDictTypeUpdModel.getRemark())
                .build();
        SysDictType oldDict = this.getById(dict.getDictId());
        sysDictDataService.updateDictDataType(oldDict.getDictType(), dict.getDictType());
        if (this.updateById(dict)) {
            List<SysDictData> dictDataList = sysDictDataService.selectDictDataByType(dict.getDictType());
            DictUtils.setDictCache(dict.getDictType(), dictDataList);
        }
    }

    /**
     * 校验字典类型称是否唯一
     *
     * @param sysDictTypeAddModel 字典类型
     *
     * @return 结果
     */
    @Override
    public boolean checkDictTypeUnique (SysDictTypeAddModel sysDictTypeAddModel) {
        Assert.notNull(sysDictTypeAddModel.getDictType(), "字典类型不可为空");
        Long dictId = StringUtils.isNull(sysDictTypeAddModel.getDictId()) ? -1L : sysDictTypeAddModel.getDictId();
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDictType::getDictType, sysDictTypeAddModel.getDictType());
        lambdaQueryWrapper.ne(sysDictTypeAddModel.getDictId() != null, SysDictType::getDictId, dictId);
        if (this.count(lambdaQueryWrapper) > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public boolean checkDictTypeUnique(SysDictTypeUpdModel sysDictTypeUpdModel) {
        Assert.notNull(sysDictTypeUpdModel.getDictType(), "字典类型不可为空");
        Long dictId = StringUtils.isNull(sysDictTypeUpdModel.getDictId()) ? -1L : sysDictTypeUpdModel.getDictId();
        LambdaQueryWrapper<SysDictType> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysDictType::getDictType, sysDictTypeUpdModel.getDictType());
        lambdaQueryWrapper.ne(sysDictTypeUpdModel.getDictId() != null, SysDictType::getDictId, dictId);
        if (this.count(lambdaQueryWrapper) > 0) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
